package org.etom.impl.ui.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.etom.connector.datatypes.IMoodleConnection;
import org.etom.impl.ui.Activator;
import org.etom.impl.ui.common.IconConstants;
import org.etom.impl.ui.common.ResourcesTreeViewer;
import org.etom.impl.ui.views.ViewsMessages;
import org.etom.impl.ui.wizards.NewAccountWizard;

public class EditAccountAction extends Action {
  
  private ResourcesTreeViewer resourcesTreeViewer;
  private Shell shell;
  
  public EditAccountAction(Shell shell, ResourcesTreeViewer resourcesTreeViewer) {
    this.shell = shell;
    this.resourcesTreeViewer = resourcesTreeViewer;
    init();
  }

  @Override
  public void run() {
    Object selection = resourcesTreeViewer.getSelection();
    if (!(selection instanceof IMoodleConnection)) return;
    IMoodleConnection[] moodleConnectionArr = {(IMoodleConnection) selection};
    NewAccountWizard wizard = new NewAccountWizard(moodleConnectionArr[0]);
    WizardDialog wizardDialog = new WizardDialog(shell, wizard);
    wizardDialog.setBlockOnOpen(true);
    if (wizardDialog.open() == SWT.CANCEL) return;
    resourcesTreeViewer.removeMoodleConnections(moodleConnectionArr);
    resourcesTreeViewer.addMoodleConnection(wizard.getMoodleConnection());
  }
  
  /*
   * The method initializes the action. 
   */
  private void init() {
    setText(ViewsMessages.Resources_Context_Menu_Edit);
    setImageDescriptor(ImageDescriptor.createFromFile(Activator.class,
            IconConstants.MENU_EDIT_ICON_PATH));
  }
  
}
